package file;

import java.io.*;
import java.util.Scanner;

/**
 * Creared with IntelliJ IDEA.
 * Description:
 * User:yxd
 * Date:2022-04-08
 * Time:16:17
 */
//进行文件内容的查找,扫描指定目录,找到名称或内容中包含指定字符的所有普通文件(不包含目录)
public class Demo15 {
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入要扫描的文件路径:");
        String rootDirPath = input.next();
        System.out.println("请输入要查询的关键字:");
        String word = input.next();
        File rootDir = new File(rootDirPath);
        if(!rootDir.isDirectory()){
            System.out.println("输入的路径非法!");
            return;
        }
        sDir(rootDir,word);
    }

    private static void sDir(File rootDir, String word) throws IOException {
        File[] files = rootDir.listFiles();
        if(files == null){
            return;
        }
        for (File f:files) {
            if(f.isDirectory()){
                sDir(f,word);
            }
            if(f.isFile()){
                //针对文件进行查找
                if(containsWord(f,word)){
                    System.out.println(f.getCanonicalPath());
                }
            }
        }
    }

    private static boolean containsWord(File f, String word) {
        StringBuilder stringBuilder = new StringBuilder();
        //把f中的内容都读出来,放到StringBuilder中,看是否包含关键字
        try(Reader reader = new FileReader(f)){
            char[] c = new char[1024];
            while(true){
                int x = reader.read(c);
                if(x == -1){
                    break;
                }
                stringBuilder.append(c,0,x);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //indexOf返回的是子串的下标,如果word存在,那么下标一定不是-1,
        return stringBuilder.indexOf(word) != -1;
    }
}
